package com.chuck.blogpro.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.chuck.blogpro.pojo.Result;
import com.chuck.blogpro.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * http 请求拦截器：Spring 层面的；过滤器 Filter，直接过滤 Http 请求
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     * 返回值：true 放行；false 不放行
     * 拦截登录状态 Jwt 来实现登录功能
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        log.info("拦截请求：{}", uri);
        if (uri.contains("login")){
            return true;
        }

        String jwt = request.getHeader("token");

        if (!StringUtils.hasLength(jwt)){
            log.info("请求头token为空");
            Result objc = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(objc);
            response.getWriter().write(jsonString);
            return false;
        }

        // 校验
        Map<String, Object> map = JWTUtils.checkToken(jwt);

        if (map == null){
            log.info("token已过期");
            Result objc = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(objc);
            response.getWriter().write(jsonString);
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
